import 'package:flutter/material.dart';
import 'package:flutter_school/utils/video_player.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import '../../http/index.dart';
import './multiple_see.dart';
import './icon.dart';
import '../../utils/video_player.dart';

class ForumPage extends StatefulWidget {
  ForumPage({Key key}) : super(key: key);

  @override
  _ForumPageState createState() => _ForumPageState();
}

class _ForumPageState extends State<ForumPage> {
  EasyRefreshController _controller;
  var postList;
  @override
  void initState() {
    super.initState();
    _controller = EasyRefreshController();
    getData();
  }

  getData() async {
    var data = await Http(context).postHttp('/bbs', {'category': 0, 'page': 1});
    setState(() {
      postList = data['data']['lists'];
    });
    print(postList);
  }

  iconData(ico) {
    print(ico);
  }

  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.white,
        elevation: 0,
        centerTitle: true,
        title: Text('圈子'),
      ),
      body: EasyRefresh(
        enableControlFinishRefresh: false,
        enableControlFinishLoad: true,
        controller: _controller,
        header: ClassicalHeader(),
        footer: ClassicalFooter(),
        child: ListView.builder(
          // cacheExtent: 20,
          itemCount: postList == null ? 0 : postList.length,
          shrinkWrap: true,
          itemBuilder: (context, index) {
            return Column(
              children: [
                index == 0 ? Special() : Text(''),
                PostItem(postList[index])
              ],
            );
          },
        ),
        onRefresh: () async {
          var data =
              await Http(context).postHttp('/bbs', {'category': 0, 'page': 1});
          setState(() {
            postList = data['data']['lists'];
          });
        },
        onLoad: () async {
          var data =
              await Http(context).postHttp('/bbs', {'category': 0, 'page': 1});
          setState(() {
            postList.addAll(data['data']['lists']);
          });
          _controller.finishLoad(success: true, noMore: false);
        },
      ),
    );
  }
}

class Special extends StatefulWidget {
  Special({Key key}) : super(key: key);

  @override
  _SpecialState createState() => _SpecialState();
}

class _SpecialState extends State<Special> {
  @override
  Widget build(BuildContext context) {
    return Container(
      padding: EdgeInsets.fromLTRB(25.w, 0, 25.w, 0),
      height: 200.h,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          InkWell(
            child: Container(
              alignment: Alignment.center,
              decoration: BoxDecoration(
                borderRadius: BorderRadius.all(Radius.circular(10)),
                image: DecorationImage(
                  image: AssetImage('assets/img/xinwen.png'),
                  fit: BoxFit.fill,
                ),
              ),
              width: 340.w,
              height: double.infinity,
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Text(
                    "学校新闻",
                    style: TextStyle(
                      fontSize: 36.sp,
                      color: Color(0xfffffffff),
                      fontWeight: FontWeight.w600,
                    ),
                    textAlign: TextAlign.start,
                  ),
                  SizedBox(height: 20.h),
                  Text(
                    'School news',
                    style: TextStyle(
                      fontSize: 28.sp,
                      color: Color(0xfffffffff),
                    ),
                    textAlign: TextAlign.start,
                  ),
                ],
              ),
            ),
            onTap: () {
              Navigator.of(context).pushNamed('/journaism');
            },
          ),
          InkWell(
            child: Container(
              alignment: Alignment.center,
              decoration: BoxDecoration(
                borderRadius: BorderRadius.all(Radius.circular(10)),
                image: DecorationImage(
                  image: AssetImage('assets/img/jiaoyu.png'),
                  fit: BoxFit.fill,
                ),
              ),
              width: 340.w,
              height: double.infinity,
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Text(
                    "教育专题",
                    style: TextStyle(
                      fontSize: 36.sp,
                      color: Color(0xfffffffff),
                      fontWeight: FontWeight.w600,
                    ),
                    textAlign: TextAlign.start,
                  ),
                  SizedBox(height: 20.h),
                  Text(
                    'Educational topics',
                    style: TextStyle(
                      fontSize: 28.sp,
                      color: Color(0xfffffffff),
                    ),
                    textAlign: TextAlign.start,
                  ),
                ],
              ),
            ),
            onTap: () {
              Navigator.of(context).pushNamed('/education');
            },
          ),
        ],
      ),
    );
  }
}

class PostItem extends StatefulWidget {
  var item;
  PostItem(this.item);
  @override
  _PostItemState createState() => _PostItemState(item);
}

class _PostItemState extends State<PostItem> {
  var item;
  List imageList = [];
  _PostItemState(this.item);
  @override
  Widget build(BuildContext context) {
    return Container(
      margin: EdgeInsets.fromLTRB(25.w, 70.h, 25.w, 0),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          InkWell(
            child: Column(
              children: [
                Row(
                  children: [
                    ClipOval(
                      child: Image.network(
                        item['account']['head_img'] != ''
                            ? item['account']['head_img']
                            : 'https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=3363295869,2467511306&fm=26&gp=0.jpg',
                        fit: BoxFit.fill,
                        width: 88.w,
                        height: 88.w,
                      ),
                    ),
                    SizedBox(width: 25.w),
                    Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(
                          item['account']['nickname'] != ''
                              ? item['account']['nickname']
                              : item['account']['name'],
                          style: TextStyle(
                            fontSize: 32.sp,
                            color: Color(0xff333333),
                            fontWeight: FontWeight.w600,
                          ),
                        ),
                        SizedBox(height: 10.h),
                        Text(
                          item['create_time'],
                          style: TextStyle(
                            fontSize: 24.sp,
                            color: Color(0xff666666),
                          ),
                        ),
                      ],
                    )
                  ],
                )
              ],
            ),
          ),
          SizedBox(height: 50.h),
          // 这里应该是自定义图标
          ExpressionText(
            item['title'],
            TextStyle(
              color: Color(0xff333333),
              fontSize: 34.sp,
              fontWeight: FontWeight.w600,
            ),
          ),
          SizedBox(height: 23.h),
          ExpressionText(
            item['content'],
            TextStyle(
              color: Color(0xff999999),
              fontSize: 28.sp,
            ),
          ),
          SizedBox(height: 24.h),
          item['type']['id'] == 1 && item['images'].length >= 1
              ? ImageSee(item['images'])
              : item['type']['id'] == 2
                  ? Container(
                      // width: 700.w,
                      height: 500.h,
                      child:
                          VideoDetailsWidget(item['video']['url'], item['id']),
                    )
                  : Text(''),
          SizedBox(height: 24.h),
          PostInfo(item['view_num'], item['reply_num'], item['fav_num'])
        ],
      ),
    );
  }
}

// 图片的显示和查看
class ImageSee extends StatefulWidget {
  List imageList = [];
  ImageSee(this.imageList);

  @override
  _ImageSeeState createState() => _ImageSeeState(imageList);
}

class _ImageSeeState extends State<ImageSee> {
  List imageList = [];
  _ImageSeeState(this.imageList);
  @override
  Widget build(BuildContext context) {
    return Container(
      child: GridView.builder(
        physics: NeverScrollableScrollPhysics(),
        shrinkWrap: true,
        itemCount: imageList.length,
        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 3,
          crossAxisSpacing: 10.w,
          mainAxisSpacing: 10.w,
        ),
        // ignore: missing_return
        itemBuilder: (context, index) {
          return InkWell(
            child: Container(
              child: ClipRRect(
                borderRadius: BorderRadius.all(Radius.circular(5)),
                child: Image.network(
                  imageList[index]['url'],
                  fit: BoxFit.fill,
                ),
              ),
            ),
            onTap: () {
              //FadeRoute是自定义的切换过度动画（渐隐渐现） 如果不需要 可以使用默认的MaterialPageRoute
              Navigator.of(context).push(new FadeRoute(
                page: PhotoViewGalleryScreen(
                  //传入图片list
                  images: imageList,
                  //传入当前点击的图片的index
                  index: index,
                  heroTag: '',
                ),
              ));
            },
          );
        },
      ),
    );
  }
}

// 点击进入图片的路由
class FadeRoute extends PageRouteBuilder {
  final Widget page;
  FadeRoute({this.page})
      : super(
          pageBuilder: (
            BuildContext context,
            Animation<double> animation,
            Animation<double> secondaryAnimation,
          ) =>
              page,
          transitionsBuilder: (
            BuildContext context,
            Animation<double> animation,
            Animation<double> secondaryAnimation,
            Widget child,
          ) =>
              FadeTransition(
            opacity: animation,
            child: child,
          ),
        );
}

// 下面的观看次数 点赞量等
// ignore: must_be_immutable
class PostInfo extends StatefulWidget {
  int lookNum;
  int replyNum;
  int favNum;
  PostInfo(this.favNum, this.lookNum, this.replyNum, {Key key})
      : super(key: key);

  @override
  _PostInfoState createState() =>
      _PostInfoState(this.favNum, this.lookNum, this.replyNum);
}

class _PostInfoState extends State<PostInfo> {
  int lookNum;
  int replyNum;
  int favNum;
  _PostInfoState(this.favNum, this.lookNum, this.replyNum);
  @override
  Widget build(BuildContext context) {
    return Container(
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Row(
            children: [
              Image.asset(
                'assets/icon/yan.png',
                alignment: Alignment.center,
                width: 38.0.w,
                height: 38.0.w,
                fit: BoxFit.cover,
              ),
              SizedBox(width: 8.5.w),
              Text(
                lookNum.toString(),
                style: TextStyle(
                  fontSize: 24.sp,
                  color: Color(0xff666666),
                ),
              ),
            ],
          ),
          Row(
            children: [
              Image.asset(
                'assets/icon/zan.png',
                alignment: Alignment.center,
                width: 38.0.w,
                height: 38.0.w,
                fit: BoxFit.cover,
              ),
              SizedBox(width: 8.5.w),
              Text(
                favNum.toString(),
                style: TextStyle(
                  fontSize: 24.sp,
                  color: Color(0xff666666),
                ),
              ),
            ],
          ),
          Row(
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              Image.asset(
                'assets/icon/xiaoxi.png',
                alignment: Alignment.center,
                width: 38.0.w,
                height: 38.0.w,
                fit: BoxFit.cover,
              ),
              SizedBox(width: 8.5.w),
              Text(
                replyNum.toString(),
                style: TextStyle(
                  fontSize: 24.sp,
                  color: Color(0xff666666),
                ),
              ),
            ],
          )
        ],
      ),
    );
  }
}
